package han.cirno.corrupt.modules.theme

import android.util.Base64
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import han.cirno.cirno_color.ColorSelector
import han.cirno.corrupt.R
import han.cirno.corrupt.activity.main.LocalBottomPadding
import han.cirno.corrupt.activity.main.LocalNavController
import han.cirno.corrupt.components.monet.MonetGenerator
import han.cirno.corrupt.components.monet.MonetPalette
import han.cirno.corrupt.compose.SimpleRadioButton
import han.cirno.corrupt.compose.VerticalSpacer
import han.cirno.corrupt.compose.builtin_theme.CorruptColor
import han.cirno.corrupt.compose.localeStringResource
import han.cirno.corrupt.data.SettingColorTheme
import han.cirno.corrupt.data.SettingKeys
import han.cirno.corrupt.getPreferenceKey
import han.cirno.corrupt.util.SerialUtil
import han.cirno.corrupt.writeDataStore
import kotlinx.coroutines.runBlocking

@Composable
fun ThemeSettingLayout()= Column(
    modifier = Modifier
        .fillMaxSize()
        .padding(horizontal = 8.dp)
        .verticalScroll(rememberScrollState())){
    var showPreview by remember { mutableStateOf(false) }
    var selectedColor by remember { mutableIntStateOf("ff4a148c".toLong(16).toInt()) }
    val colorGroups=ColorSelector.colors.asSequence().groupBy { c->c.first.split("_")[0] }
    var monetPalette by remember { mutableStateOf(CorruptColor.defaultMonetPalette as MonetPalette) }
    val toneSelectState = remember { mutableIntStateOf(0) }
    val navController= LocalNavController.current
    Column(modifier = Modifier.border(
        width = 1.dp,
        color = MaterialTheme.colorScheme.outline,
        shape = RoundedCornerShape(4.dp)
    )) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(text= localeStringResource(R.string.settings_theme_custom_color_scheme_sub_title),
                style = MaterialTheme.typography.titleLarge)
            VerticalSpacer(8.dp)
            Row(modifier = Modifier.fillMaxWidth()) {
                colorGroups.keys.forEach { k ->
                    Column(modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)) {
                        colorGroups[k]?.forEach { cp ->
                            val color = cp.second or 0xFF000000.toInt()
                            Box(
                                modifier = Modifier
                                    .height(32.dp)
                                    .fillMaxWidth()
                                    .background(color = Color(color))
                                    .clickable {
                                        selectedColor = color
                                        showPreview = true
                                    })
                        }
                    }
                }
            }
        }
    }
    AnimatedVisibility(visible = showPreview) { Column{
        VerticalSpacer(16.dp)
        LaunchedEffect(selectedColor,toneSelectState.intValue) {
            monetPalette = MonetGenerator.generateColors(selectedColor, selectedColor,when(toneSelectState.intValue){
                1->MonetGenerator.ColorTone.SYSTEM_ACCENT_1
                2->MonetGenerator.ColorTone.SYSTEM_ACCENT_2
                3->MonetGenerator.ColorTone.SYSTEM_ACCENT_3
                else->MonetGenerator.ColorTone.DEFAULT
            })
        }
        Column(modifier = Modifier.border(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline,
            shape = RoundedCornerShape(4.dp)
        )) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(text= localeStringResource(R.string.settings_theme_custom_color_scheme_sub_tone_title),
                    style = MaterialTheme.typography.titleLarge)
                VerticalSpacer(8.dp)
                SimpleRadioButton(R.string.settings_theme_custom_color_scheme_sub_tone_default,0,toneSelectState)
                SimpleRadioButton(R.string.settings_theme_custom_color_scheme_sub_tone_accent_1,1,toneSelectState)
                SimpleRadioButton(R.string.settings_theme_custom_color_scheme_sub_tone_accent_2,2,toneSelectState)
                SimpleRadioButton(R.string.settings_theme_custom_color_scheme_sub_tone_accent_3,3,toneSelectState)
            }
        }
        VerticalSpacer(16.dp)
        Column(modifier = Modifier.border(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline,
            shape = RoundedCornerShape(4.dp)
        )) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(text= localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_title),
                    style = MaterialTheme.typography.titleLarge)
                VerticalSpacer(8.dp)
                ThemePaletteTester(colorScheme = monetPalette.lightScheme)
                VerticalSpacer(8.dp)
                ThemePaletteTester(colorScheme = monetPalette.darkScheme)
            }
        }
        VerticalSpacer(16.dp)
        Column(modifier = Modifier.border(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline,
            shape = RoundedCornerShape(4.dp)
        )) {
            fun saveAction(){
                runBlocking {
                    writeDataStore(
                        getPreferenceKey(SettingKeys.RAW_USER_COLOR_SCHEME),
                        Base64.encodeToString(
                            SerialUtil.serialize(monetPalette),
                            Base64.DEFAULT
                        )
                    )
                }
                navController.popBackStack()
            }
            fun applyAction(){
                runBlocking {
                    writeDataStore(
                        getPreferenceKey(SettingKeys.SELECT_COLOR_SCHEME),
                        SettingColorTheme.CUSTOMIZE
                    )
                }
            }
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = localeStringResource(R.string.settings_theme_custom_color_scheme_sub_apply_title),
                    style = MaterialTheme.typography.titleLarge
                )
                VerticalSpacer(8.dp)
                Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                    OutlinedButton(
                        modifier = Modifier.weight(0.4f),
                        onClick = { saveAction() }) {
                        Text(
                            text = localeStringResource(R.string.settings_theme_custom_color_scheme_sub_apply_save),
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                    Button(
                        modifier = Modifier.weight(0.6f),
                        onClick = { applyAction();saveAction() }) {
                        Text(
                            text = localeStringResource(R.string.settings_theme_custom_color_scheme_sub_apply_save_apply),
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
            }
        }
    }}
    VerticalSpacer(LocalBottomPadding.current)
}

@Composable
fun ThemePaletteTester(
    modifier: Modifier = Modifier,
    colorScheme: ColorScheme = MaterialTheme.colorScheme
) =MaterialTheme(colorScheme=colorScheme){
    val checked = remember { mutableStateOf(true) }
    val sliderValue = remember { mutableFloatStateOf(50f) }
    Card(colors = CardDefaults.cardColors(
        containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(4.dp)) { Column(
        modifier = modifier.padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ){
        Text(
            text = localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_card_title),
            style = MaterialTheme.typography.titleLarge,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.padding(8.dp)
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            FilledTonalButton(
                onClick = {},
                modifier = Modifier.weight(1f)
            ) {
                Icon(Icons.Default.Favorite, contentDescription = null)
                Spacer(Modifier.width(4.dp))
                Text(
                    localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_button_primary))
            }

            OutlinedButton(
                onClick = {},
                modifier = Modifier.weight(1f)
            ) { Text(localeStringResource(
                R.string.settings_theme_custom_color_scheme_sub_test_button_secondary)) }
        }
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Checkbox(
                checked = checked.value,
                onCheckedChange = { checked.value = it }
            )
            Text(
                localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_checkbox))
        }
        Slider(
            value = sliderValue.floatValue,
            onValueChange = { sliderValue.floatValue = it },
            valueRange = 0f..100f,
            modifier = Modifier.fillMaxWidth()
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            ColorSample(
                localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_box_primary),
                MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)
            ColorSample(
                localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_box_container),
                MaterialTheme.colorScheme.primaryContainer, MaterialTheme.colorScheme.onPrimaryContainer)
            ColorSample(
                localeStringResource(R.string.settings_theme_custom_color_scheme_sub_test_box_surface),
                MaterialTheme.colorScheme.surface, MaterialTheme.colorScheme.onSurface)
        }
    }}
}

@Composable
private fun RowScope.ColorSample(
    label: String,
    backgroundColor: Color,
    contentColor: Color,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .weight(1f)
            .height(48.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(backgroundColor, shape = RoundedCornerShape(2.dp)),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.labelSmall,
                color = contentColor
            )
        }
    }
}